package net.tools;

import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.WritableFont;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;


public class GridExportUtil {

    private int rowsHeight = 400; // 单行高度

    private HttpServletRequest request;

    private HttpServletResponse response;


    public GridExportUtil(HttpServletRequest request, HttpServletResponse response) {
        setRequest(request);
        setResponse(response);
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public void exportXLS(List data, Class beanClass) throws IOException {
//		List cols = this.getDisplayColumnInfo();
//		int len = cols.size();
//		int len = 12;
//		String[] properiesName = new String[len];
//		String[] headsName = new String[len];
////		List titlelist = new ArrayList();
//		for (int i = 0; i < len; i++) {
////			ColumnInfo colInfo = (ColumnInfo) cols.get(i);
//			properiesName[i] = colInfo.getFieldIndex();
//			headsName[i] = colInfo.getHeader();
////			titlelist.add(map);
//		}

        //properiesName 数据id  headsName title
//		exportXLS(data, properiesName, headsName, beanClass);
    }


    /**
     * 导出xls文件
     *
     * @param data          导出的数捄1?7 list<Object>
     * @param properiesName map的key
     * @param headsName     key对应的title
     * @param beanClass     Object类型
     * @throws java.io.IOException
     */
    public void exportXLS(String title, List data, String[] properiesName,
                          String[] headsName, int[] colswidth, String[] aligns, Class beanClass) throws IOException {
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bos = null;
        jxl.write.WritableWorkbook wwb = null;
        jxl.write.WritableSheet ws = null;
        try {
            baos = new ByteArrayOutputStream();
            bos = new BufferedOutputStream(baos);
            wwb = Workbook.createWorkbook(bos);
            ws = wwb.createSheet("当前数据", 0);
            setExcel(title, data, properiesName, headsName, colswidth, aligns, ws, 1);
            wwb.write();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            bos.close();
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            byte[] bs = baos.toByteArray();
            outPutExcel("data.xls", bs); // 输出文件
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }


    /**
     * 设置excel字段
     *
     * @return byte[]
     * @throws Exception
     */
    private int setExcel(String bigtitle, List valueList, String[] properiesName,
                         String[] headsName, int[] colswidth, String[] aligns, jxl.write.WritableSheet ws, int rownum)
            throws Exception {
        try {
            int[] colsWidth = new int[headsName.length];
            if (colswidth != null) {
                colsWidth = colswidth;
            }
            // 列宽设置
            bigtitle = convert(bigtitle);
            //合并单元格
            if ("".equals(bigtitle)) {
                rownum = 0;
            } else {
//		  设置大标题栏样式
                jxl.write.WritableFont wfcdtt = new jxl.write.WritableFont(
                        WritableFont.ARIAL, 20, WritableFont.BOLD, false,
                        UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
                jxl.write.WritableCellFormat wcfFCdtt = new jxl.write.WritableCellFormat(
                        wfcdtt);
                wcfFCdtt.setAlignment(jxl.format.Alignment.CENTRE);
                wcfFCdtt.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
                // 设置标题栄1?7
                jxl.write.Label headdttCell = new jxl.write.Label(0, 0,
                        bigtitle, wcfFCdtt);
                ws.addCell(headdttCell);
                ws.mergeCells(0, 0, headsName.length - 1, 0);
                ws.setRowView(0, rowsHeight + rowsHeight);
            }

            // 设置标题栏样式
            jxl.write.WritableFont wfc = new jxl.write.WritableFont(
                    WritableFont.ARIAL, 10, WritableFont.BOLD, false,
                    UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
            jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(
                    wfc);
            wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
            wcfFC.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            // 设置标题
            for (int i = 0; i < headsName.length; i++) {
                String title = (String) headsName[i];
                title = convert(title);
                jxl.write.Label headCell = new jxl.write.Label(i, 0 + rownum,
                        title, wcfFC);
                ws.addCell(headCell);
            }
            jxl.write.WritableCellFormat cellFormat = new jxl.write.WritableCellFormat();
            cellFormat.setBorder(jxl.format.Border.ALL,
                    jxl.format.BorderLineStyle.THIN);


            // 设置数据区域
            int size = valueList.size();
            for (int i = 0; i < size; i++) {
                Map map = (Map) valueList.get(i);
                for (int j = 0; j < properiesName.length; j++) {
                    String value = "";
                    String key = properiesName[j];
                    String straligns = aligns[j];
//				if("RIGHT".equals(straligns)){
//					cellFormat.setAlignment(jxl.format.Alignment.RIGHT);
//				}else if("CENTER".equals(straligns)){
//					cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
//				}else{
//					cellFormat.setAlignment(jxl.format.Alignment.LEFT);
//				}

                    try {
                        value = String.valueOf((map.get(key) == null ? "" : map.get(key)));
                        value = convert(value);
                    } catch (Exception e) {
                        e.printStackTrace();
                        value = "";
                    }
                    try {
                        jxl.write.Label datCell = new jxl.write.Label(j,
                                i + 1 + rownum, value, cellFormat);
                        ws.addCell(datCell);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            //设置列宽
            for (int i = 0; i < colsWidth.length; i++) {
                if (colsWidth[i] < 16) {
                    colsWidth[i] = 16;
                }
                ws.setColumnView(i, colsWidth[i]);
            }
            //设置列高
            for (int i = 0; i <= valueList.size(); i++) {
                ws.setRowView(i + rownum, rowsHeight);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rownum + valueList.size() + 1;
    }


    /**
     * 把计算结果输出到Excel
     */
    public void outPutExcel(String fileName, byte[] bs) throws Exception {
        javax.servlet.ServletOutputStream outfile = null;
        try {
            getResponse().reset();
            String CONTENT_TYPE = "text/html; charset=UTF-8";
            getResponse().setContentType(CONTENT_TYPE);
            getResponse().setContentType("application/octet-stream");
            getResponse().setHeader("Content-Disposition",
                    "attachment; filename=\"" + fileName + "\"");
            outfile = getResponse().getOutputStream();
            outfile.write(bs);
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            outfile.close();
        }
    }


    public String convert(String str) {
//        if (str == null)
//            str = "";
//        str = str.trim();
//        if (str.length() > 0) {
//            try {
//                str = new String(str.getBytes("ISO-8859-1"), "GBK");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        return str;
    }
}
